﻿/*
COPYRIGHT (C) 2011-2012 Raynald Messié

THIS FILE IS PART OF SCRUMPILOT.

SCRUMPILOT IS FREE SOFTWARE: YOU CAN REDISTRIBUTE IT AND/OR MODIFY IT UNDER THE TERMS OF 
THE GNU LESSER GENERAL PUBLIC LICENSE VERSION v2.1 AS PUBLISHED BY THE FREE SOFTWARE FOUNDATION.

SCRUMPILOT IS DISTRIBUTED IN THE HOPE THAT IT WILL BE USEFUL, BUT WITHOUT ANY WARRANTY; WITHOUT
EVEN THE IMPLIED WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. SEE THE GNU LESSER
GENERAL PUBLIC LICENSE FOR MORE DETAILS.

YOU SHOULD HAVE RECEIVED A COPY OF THE GNU LESSER GENERAL PUBLIC LICENSE ALONG WITH SCRUMPILOT. 
IF NOT, SEE <HTTP://WWW.GNU.ORG/LICENSES/>.
*/

function CallService(varType, varUrl, varData, varProcessData, successFunc) {
    if (varType == "POST")
        varData = JSON.stringify(varData);
    return $.ajax({
        type: varType, //GET or POST or PUT or DELETE verb
        url: varUrl, // Location of the service
        data: varData, //Data sent to server
        contentType: "application/json; charset=utf-8", // content type sent to server
        dataType: "json", //Expected data format from server
        processdata: varProcessData, //True or False
        success: successFunc, //On Successfull service call
        error: function (data) //When Service call fails
        {
            alert(data.responseText);
        }
    });
}

function InitButtonsPage() {
    $(".linkButton").button({ icons: { primary: "ui-icon-home" } });
    $("#submitSave,#ModifyButton").button({ icons: { primary: "ui-icon-disk" } });
    $("#NewButton").button({ icons: { primary: "ui-icon-circle-plus" } });
    $(".CheckButton").button({ icons: { primary: "ui-icon-circle-check" } });
    $(".EditButton").button({ icons: { primary: "ui-icon-pencil" } });
    $(".DeleteButton").button({ icons: { primary: "ui-icon-trash" } });
    $(".followbutton").button({ icons: { primary: "ui-icon-circle-check" } });
    $(".unfollowbutton").button({ icons: { primary: "ui-icon-circle-close" } });
}

function OpenDialog(dialogName) {
    try {
        var d = $('#' + dialogName);
        d.dialog({
            autoOpen: false,
            modal: true
        }).dialog('open');
    } catch (e) {
    }
    return false;
}

function startSave() {
    $.unblockUI();
    BlockUi();
}

function endSave() {
    $.unblockUI();
    $.growlUI('Saved successfull', 'Saved');
}

function noSave() {
    $.unblockUI();
    alert("Save failed");
}

function LoadHtmlAndTemplate(url, elementName, data, empty, callback) {
    // Load template and use it
    $.get(url, function (html) {
        if (empty)
            $("#" + elementName).empty();
        $.tmpl(html, data).appendTo("#" + elementName);
        $('abbr.timeago').timeago();
        InitButtonsPage();
        callback && callback();
    });
}

function setTemplate(templateName, elementName, data, empty) {
    if (empty)
        $("#" + elementName).empty();
    $("#" + templateName).tmpl(data).appendTo("#" + elementName);
    $('abbr.timeago').timeago();
    InitButtonsPage();
}

function loadAjaxHtml(destination, uri, loadingDiv, callback) {
    if (!loadingDiv || loadingDiv == "")
        loadingDiv = destination;
    if (loadingDiv != 'none')
        BlockUi(loadingDiv);

    $("#" + destination).load(uri, function (html) {
        if (html.length > 0) {
            $("#" + destination).html(html);
            $('abbr.timeago').timeago();
            if (loadingDiv != 'none')
                $("#" + loadingDiv).unblock();
            callback && callback();
        }
    });
}

function BlockUi(elem) {
    if (!elem || elem == '')
        elem = 'body';
    var option = ({
        css: {
            border: 'none',
            padding: '15px',
            backgroundColor: '#000',
            '-webkit-border-radius': '10px',
            '-moz-border-radius': '10px',
            opacity: .5,
            color: '#fff'
        },
        message: $('#BlockUIMessage')
    });
    if (elem)
        if (elem.jquery)
            return elem.block(option);
        else
            return $("#" + elem).block(option);
    else
        return $.blockUI(option);
}

function isChecked(name) {
    return $(name).is(":checked");
}

function setScore(id, score, gUrlSetScore) {
    $("#dialog-score").empty();
    return $.ajax({
        url: gUrlSetScore,
        data: { id: id },
        success: function (htmldata) {
            $.unblockUI();
            $('#dialog-score').html(htmldata);
            setRaty('#stLevel', '#Level', ['Easy', 'Normal', 'Hard']);
            setRaty('#stPriority', '#Priority', ['Low', 'Normal', 'High']);
            setRaty('#stDuration', '#Duration', ['Short', 'Normal', 'Long']);
            $('#dialog-score').dialog(
                {
                    autoOpen: false,
                    width: 300,
                    modal: true,
                    hide: "highlight",
                    buttons: {
                        Cancel: function () { $(this).dialog("close"); },
                        "Save": function () { $("#ScoreForm").submit(); }
                    }
                }).dialog('open');
            $("#actualScore").text(score.toString());
        }
    });
}

function setRaty(elem, valtarget, hint) {
    var startValue = parseInt($(valtarget).val());
    var spRange = new Array(1, 3, 5);
    startValue = spRange.indexOf(startValue) + 1;
    $(elem).raty(
                {
                    number: 3,
                    hintList: hint,
                    path: g_ImgDirectory,
                    starOn: 'star-on-big.png',
                    starOff: 'star-off-big.png',
                    target: elem + 'Int',
                    targetKeep: true,
                    size: 24,
                    start: startValue,
                    click: function (score) {
                        score = parseInt(score) - 1;
                        //alert('ID: ' + this.attr('id') + '\nscore: ' + SPRange[score] + '\nevent: ' + evt);
                        $(valtarget).val(spRange[score]);
                        changeScore();
                    }
                });
    $(elem).trigger('mouseout'); // Force hint load
}

function changeScore() {
    $("#actualScore").text(parseInt($("#Level").val()) * parseInt($("#Priority").val()) * parseInt($("#Duration").val()));
}

// Add some helpers for JSRender
$.views.helpers({
    format: function (val, format) {
        if (format == "date" && val && val != "") {
            // format ISO 8601 dateTime in local Date Time
            var date = new Date(val);
            return date.toLocaleDateString();
        }
        return '';
    }
});